package mspbots.hubspot.client.core.app;

import lombok.RequiredArgsConstructor;
import mspbots.hubspot.client.core.AbstractToolsUtil;
import mspbots.hubspot.client.core.contacts.ContactsServiceImpl;
import mspbots.hubspot.common.RedisKeys;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * mspbots.data.mspbots.data.hubspot.core.app.AutoTaskService
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/7/15
 */
@Service
@RequiredArgsConstructor
public class HubSpotService extends AbstractToolsUtil {

    private final ContactsServiceImpl contactsService;

    public Mono<Boolean> testClient(Long tenantId) {
        return this.contactsService.properties(tenantId)
                .collectList()
                .map(list -> list.size() > 0);
    }

    public Mono<Boolean> onOffTenant(Long tenantId, String onOff) {
        if ("ON".equals(onOff.toUpperCase())) {
            return this.stringRedisTemplate.opsForValue()
                    .set(RedisKeys.ON_OFF_TENANT_TASK_REDIS_KEY + ":" + tenantId, onOff.toUpperCase(),
                            Duration.ofDays(365));
        } else {
            return this.stringRedisTemplate.opsForValue()
                    .delete(RedisKeys.ON_OFF_TENANT_TASK_REDIS_KEY + ":" + tenantId);
        }
    }

    public Mono<Boolean> synchronise(Long tenantId) {
        return this.stringRedisTemplate.opsForValue()
                .delete(RedisKeys.TICKETS_ANCHOR_REDIS_KEY_PREFIX + tenantId)
                .flatMap(r -> this.stringRedisTemplate.opsForValue()
                        .delete(RedisKeys.COMPANIES_ANCHOR_REDIS_KEY_PREFIX + tenantId))
                .flatMap(r -> this.stringRedisTemplate.opsForValue()
                        .delete(RedisKeys.CONTACTS_ANCHOR_REDIS_KEY_PREFIX + tenantId));

    }
}
